package com.boomsecret.utils;

import org.apache.commons.lang3.StringUtils;

/**
 * Created by wangjinliang on 2018/1/5.
 */
public final class IPUtils {

    private IPUtils() { }

    public static long ip2Long(String ipAddress) {
        if (StringUtils.isBlank(ipAddress)) {
            return 0;
        }
        long result = 0;
        String[] ipAddressInArray = ipAddress.split("\\.");
        for (int i = 3; i >= 0; i --) {
            long ip = Long.parseLong(ipAddressInArray[3 - i]);
            result |= ip << (i * 8);
        }
        return result;
    }

    public static String long2Ip(long ip) {
        StringBuilder sb = new StringBuilder(15);
        for (int i = 0; i < 4; i++) {
            sb.insert(0, Long.toString(ip & 0xff));
            if (i < 3) {
                sb.insert(0, '.');
            }
            ip = ip >> 8;
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        long longIP = ip2Long("255.102.11.10");
        System.out.println(longIP);
        System.out.println(long2Ip(longIP));
    }
}
